import 'dart:io';

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_advanced_seekbar/flutter_advanced_seekbar.dart';
import 'package:flutter_app/util/LogUtil.dart';
import 'package:image_picker/image_picker.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:video_player/video_player.dart';

class HotWidget extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _HotState();
  }
}

class _HotState extends State<HotWidget> {
  @override
  void initState() {
    super.initState();
    //初始化状态
    LogUtil.init(isDebug: true);
  }

  /// 视频播放器控制器
  VideoPlayerController? _controller;
  VideoPlayerController? _toBeDisposed;

  /// 图片选择器
  final ImagePicker _picker = ImagePicker();

  /// 定义错误信息
  String? _retrieveDataError;

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        Container(
          color: Colors.black,
          child: GestureDetector(
            // onDoubleTap: _playOrPause(),
            child: Container(
              alignment: Alignment.center,
              height: 400,
              child: defaultTargetPlatform == TargetPlatform.android
                  ? FutureBuilder(
                      future: retrieveLostData(),
                      builder: (BuildContext context, AsyncSnapshot snapshot) {
                        LogUtil.v("视频回调回来。。。+ ${snapshot.connectionState}");
                        switch (snapshot.connectionState) {
                          case ConnectionState.none:
                          case ConnectionState.waiting:
                            return const Text(
                              "You have not yet picked an image",
                              textAlign: TextAlign.center,
                            );
                          case ConnectionState.done:
                            LogUtil.v("_previewVideo");
                            return _previewVideo();
                          default:
                            if (snapshot.hasError) {
                              return Text(
                                "Pick image/video error:${snapshot.error}",
                                textAlign: TextAlign.center,
                              );
                            } else {
                              return const Text(
                                "You have not yet picked an image",
                                textAlign: TextAlign.center,
                              );
                            }
                        }
                      },
                    )
                  : _previewVideo(),
            ),
          ),
        ),

        ///影片选择
        Visibility(
          visible: getVideo(),
          child: Positioned(
              left: 20,
              right: 20,
              top: 480,
              bottom: 80,
              child: _bottomWidget()),
        ),

        ///拍摄，选择图片按钮
        Positioned(
            left: 0,
            right: 0,
            top: 560,
            bottom: 0,
            child: _bottomContainer(context))
      ],
    );
  }

  var value = 0.0;

  ///底部控件
  _bottomWidget() {
    return AdvancedSeekBar(
      Colors.red,
      10,
      Colors.blue,
      lineHeight: 5,
      defaultProgress: 50,
      scaleWhileDrag: true,
      percentSplit: 10,
      percentSplitColor: Colors.green,
      percentSplitWidth: 1,
      seekBarStarted: () {},
      seekBarProgress: (v) {},
      seekBarFinished: (v) {},
    );
  }

  ///底部控件
  _bottomContainer(BuildContext context) {
    return Container(
      alignment: Alignment.center,
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          _buildWidget(context, Icons.photo, "选择视频"),
          _buildWidget(context, getIcon(), "播放"),
          _buildWidget(context, Icons.video_call, "录制"),
        ],
      ),
    );
  }

//自定义控件
  _buildWidget(BuildContext context, IconData icon, String text) {
    return Container(
      alignment: Alignment.center,
      width: MediaQuery.of(context).size.width / 3,
      child: GestureDetector(
        child: Column(
          children: [
            Icon(
              icon,
              size: 30,
              color: Colors.white,
            ),
            Text(
              text,
              style: TextStyle(color: Colors.white),
            ),
          ],
        ),
        onTap: () {
          _buildOnTap(text);
        },
      ),
    );
  }

  ///点击事件
  void _buildOnTap(String text) {
    switch (text) {
      case "选择视频":
        _onImageButtonPressed(ImageSource.gallery);
        break;
      case "录制":
        _onImageButtonPressed(ImageSource.camera);
        break;
      case "播放":
        _playOrPause();
        break;
    }
  }

  /// 选择图片、视频，拍摄视频、照片
  void _onImageButtonPressed(ImageSource source,
      {BuildContext? context}) async {
    //检查是否已有读写内存权限
    var permissionStatus = await Permission.camera.request();
    if (permissionStatus == PermissionStatus.granted) {
      if (_controller != null) {
        /// 让其静音
        await _controller?.setVolume(0.0);
      }

      /// 选择或拍摄视频的处理
      /// 限制视频为10秒
      final PickedFile? file = await _picker.getVideo(
          source: source, maxDuration: Duration(seconds: 10));

      /// 返回到此界面时就播放
      await _playVideo(file!);
    }
  }

  /// 获得丢失的数据
  Future<void> retrieveLostData() async {
    final LostData response = await _picker.getLostData();
    if (response.isEmpty) {
      LogUtil.v("retrieveLostData " + response.exception!.code);
      _retrieveDataError = response.exception?.code;
      return;
    }
    if (response.file != null) {
      if (response.type == RetrieveType.video) {
        /// 播放视频
        // ignore: unnecessary_statements
        LogUtil.v("播放视频---- ");
        await _playVideo(response.file);
      }
    } else {
      LogUtil.v("retrieveLostData " + response.exception!.code);
      _retrieveDataError = response.exception!.code;
    }
  }

  /// 播放视频
  Future<void> _playVideo(PickedFile? file) async {
    /// mounted true 表示当前state仍然在widget tree上
    if (file != null && mounted) {
      /// 重置视频播放器控制器
      await _disposeVideoController();
      if (kIsWeb) {
        /// kIsWeb true表示是web应用
        _controller = VideoPlayerController.network(file.path);

        /// 设置音量为0
        await _controller?.setVolume(0.0);
      } else {
        /// 非web应用
        _controller = VideoPlayerController.file(File(file.path));

        /// 设置音量为1.0
        await _controller?.setVolume(1.0);
      }
      LogUtil.v("_playVideo---- ");
      await _controller?.initialize();
      await _controller?.setLooping(true);
      await _controller?.play();

      /// 更新UI
      setState(() {});
    }
  }

  /// 预览视频
  Widget _previewVideo() {
    /// 获取错语信息
    final Text? retrieveError = _getRetrieveErrorWidget();
    if (retrieveError != null) {
      LogUtil.v("retrieveError ${retrieveError.toString()}");

      /// 有错误信息则显示错误信息
      return retrieveError;
    }
    if (_controller == null) {
      /// 如果视频播放器控制器为空，则提示用户选择视频
      LogUtil.v("_controller为空 ");
      return Container(
        alignment: Alignment.center,
        child: Text(
          "You have not yet picked a vide",
          style: TextStyle(color: Colors.white),
          textAlign: TextAlign.center,
        ),
      );
    }
    return Padding(
      padding: const EdgeInsets.all(10.0),
      child: AspectRatioVideo(_controller!),
    );
  }

  Text? _getRetrieveErrorWidget() {
    if (_retrieveDataError != null) {
      final Text result = Text(_retrieveDataError!);
      _retrieveDataError = null;
      return result;
    }
    return null;
  }

  /// 重置视频播放器控制器
  Future<void> _disposeVideoController() async {
    if (_toBeDisposed != null) {
      await _toBeDisposed?.dispose();
    }
    _toBeDisposed = _controller;
    _controller = null;
  }

  ///播放或者暂停
  _playOrPause() async {
    if (_controller != null) {
      if (_controller?.value != null) {
        if (_controller!.value.isInitialized) {
          LogUtil.v("_playOrPause ${_controller?.value.isPlaying}");
          if (!_controller!.value.isPlaying) {
            // _controller.play();
            var position = _controller?.value.position;
            _controller?.seekTo(position!);
            _controller?.play();
          } else {
            _controller?.pause();
          }
        }
        // else {
        //   await _controller.initialize();
        //   //暂时屏蔽
        //   // await _controller.setLooping(true);
        //   await _controller.play();
        // }
      }
    }
    setState(() {});
  }

  ///根据播放状态获取图片
  IconData getIcon() {
    if (_controller != null) {
      if (_controller?.value != null) {
        if (_controller!.value.isPlaying) {
          return Icons.play_circle_fill;
        } else {
          return Icons.pause_circle_filled;
        }
      }
    }
    return Icons.play_circle_fill;
  }

  ///有视频资源才显示进度条
  bool getVideo() {
    if (_controller != null) {
      return true;
    }
    return false;
  }
}

/// 自定义一个Widget，用于播放视频
class AspectRatioVideo extends StatefulWidget {
  AspectRatioVideo(this.controller);

  final VideoPlayerController controller;

  @override
  _AspectRatioVideoState createState() => _AspectRatioVideoState();
}

class _AspectRatioVideoState extends State<AspectRatioVideo> {
  /// 只读
  VideoPlayerController get controller => widget.controller;
  bool initialized = false;

  @override
  void initState() {
    super.initState();
    LogUtil.init(isDebug: true);
    LogUtil.v("_AspectRatioVideoState--initState");
    controller.addListener(_onVideoControllerUpdate);
  }

  /// 更新
  void _onVideoControllerUpdate() {
    if (!mounted) {
      return;
    }
    if (initialized != controller.value.isInitialized) {
      LogUtil.v("_AspectRatioVideoState--initialized");
      initialized = controller.value.isInitialized;

      /// 更新UI
      setState(() {});
    }
  }

  @override
  Widget build(BuildContext context) {
    LogUtil.v("_AspectRatioVideoState build --");
    if (initialized) {
      return Center(
        child: AspectRatio(
          child: VideoPlayer(controller),
          aspectRatio: controller?.value!.aspectRatio ?? 0.0,
        ),
      );
    } else {
      if (controller != null) {
        LogUtil.v("_AspectRatioVideoState 视频停止画面 --");
        return AspectRatio(
          child: VideoPlayer(controller),
          aspectRatio: controller?.value?.aspectRatio ?? 0.0,
        );
      }
      LogUtil.v("_AspectRatioVideoState Container--");
      return Container();
    }
  }

  /// 关闭时，清理工作
  @override
  void dispose() {
    controller.removeListener(_onVideoControllerUpdate);
    super.dispose();
  }
}
